package com.leesche.zcsp.node.web.controller.web.v2.systemsetup;

import com.leesche.zcsp.node.app.v1.timer.PhoneCodeCacheTimer;
import com.leesche.zcsp.node.app.v1.timer.VaildPhone;
import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.gernerator.TimeGreaterUilt;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.controller.sms.SmsController;
import com.leesche.zcsp.node.web.model.*;
import com.leesche.zcsp.node.web.service.*;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import com.leesche.zcsp.node.web.service.impl.data.writ.AddUserInfoCommand;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.Principal;
import com.leesche.zcsp.node.web.vo.v2.FactoryUserVo;
import com.leesche.zcsp.node.web.vo.v2.Menu;
import com.leesche.zcsp.node.web.vo.v2.RoleVo;
import com.leesche.zcsp.node.web.vo.v2.UserBusinessInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Jerry Chan
 * @version V1.0
 *          ************ * Jerry Chan: * 2016/12/7 14:52: * 创建该类并实现业务逻辑: *********
 * @Title: WebIndividualController.java
 * @Description: TODO( “系统设置”Controller类)
 * @date 2016/12/7 14:52
 */
@Controller
@RequestMapping("/v2/factory/systemsetup")
public class WebSystemSetupController {

    private static final Logger logger = Logger.getLogger(WebSystemSetupController.class);

    @Autowired
    private PrivilegeService privilegeService;

    @Autowired
    private SysUserService sysUserService;

    private static final String FACTORY_SYSTEMSETUP_CHANGEMOBILE = "web/v2/systemsetup/factory/system_changemobile";
    private static final String FACTORY_SYSTEMSETUP_CHANGELOGINPASS = "web/v2/systemsetup/factory/system_changeloginpass";

    /**
     * @Title: showRateManageView(Model model)
     * @Description: TODO(显示增加系统用户角色界面)
     * @author Jerry Chan
     * @date 2016/12/12 19:40
     */
    @RequestMapping(value = "/changemoblie", method = RequestMethod.GET)
    public String showChangeMobileView(Model model) {
        return FACTORY_SYSTEMSETUP_CHANGEMOBILE;
    }

    /**
     * @Title: showRateManageView(Model model)
     * @Description: TODO(显示增加系统用户角色界面)
     * @author Jerry Chan
     * @date 2016/12/12 19:40
     */
    @RequestMapping(value = "/changeloginpass", method = RequestMethod.GET)
    public String showChangeLoginPassView(Model model) {
        return FACTORY_SYSTEMSETUP_CHANGELOGINPASS;
    }

    /**
     * @Title: changeMobileNumber(String mobileCode, String mobileNumber, HttpSession session)
     * @Description: TODO(更换当前用户的手机号码)
     * @author Jerry Chan
     * @date 2016/12/15 21:25
     */
    @ResponseBody
    @RequestMapping(value = "changmobile", method = RequestMethod.POST)
    public Map<String, Object> changeMobileNumber(String mobileCode, String mobileNumber) {
        try {
            if (mobileCode == null || "".equals(mobileCode)) {
                return WebResult.failure("短信验证码不能为空").toMap();
            }
            if (mobileNumber == null || "".equals(mobileNumber)) {
                return WebResult.failure("手机号码不能为空").toMap();
            }
            SysUser user = new SysUser();
            user.setMobile(mobileNumber);
            if (sysUserService.findUserByUsername(user) != null) {
                return WebResult.failure("手机号已被使用,请更换其他手机号").toMap();
            }

            user = sysUserService.selectByPrimaryKey(privilegeService.getCurrentPrincipal().getUserid());
            VaildPhone validPhone = PhoneCodeCacheTimer.get(mobileCode);
            if (validPhone == null) {
                return WebResult.failure("验证码错误,请重新输入").toMap();
            } else if (validPhone.getValidTime() < new Date().getTime()) {
                PhoneCodeCacheTimer.remove(mobileCode);
                return WebResult.failure("短信验证码已过期，请重新获取").toMap();
            }else{
                if (user == null || "".equals(user.getMobile())) {
                    return WebResult.failure("用户没有手机号码").toMap();
                }else if (!validPhone.getPhone().equals(user.getMobile())) {
                    return WebResult.failure("与获取短信的手机号码一致").toMap();
                } else {
                    PhoneCodeCacheTimer.remove(mobileCode);
                }
            }

            SysUser newUser = new SysUser();
            newUser.setUserid(user.getUserid());
            newUser.setAdminid(user.getUserid());
            newUser.setUpdatetime(new Date());
            user.setMobile(mobileNumber);
            if(sysUserService.updateByPrimaryKeySelective(user) > 0){
                return WebResult.success().toMap();
            }else{
                return WebResult.failure("更改手机号码失败，请与管理员联系").toMap();
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }


    /**
     * @Title: changLoginPassword(String mobileCode, String oldpassword, String newpassword, HttpSession session)
     * @Description: TODO(修改当前用户的登录密码)
     * @author Jerry Chan
     * @date 2016/12/15 21:25
     */
    @ResponseBody
    @RequestMapping(value = "changeloginpassword", method = RequestMethod.POST)
    public Map<String, Object> changLoginPassword(String mobileCode, String oldpassword, String newpassword) {
        try {
            return this.changePassword(1, mobileCode, oldpassword, newpassword);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @param passwordType 密码类型（1.登录密码 / 2.提现密码）
     * @param mobileCode   手机号码
     * @param oldpassword  旧密码
     * @param newpassword  新密码
     * @return
     * @Title: changePassword(int passwordType, String mobileCode, String oldpassword, String newpassword, HttpSession session)
     * @Description: TODO(修改密码)
     * @author Jerry Chan
     * @date 2016/12/20 11:26
     */
    private Map<String, Object> changePassword(int passwordType, String mobileCode, String oldpassword, String
            newpassword) throws Exception {

        if (mobileCode == null || "".equals(mobileCode)) {
            return WebResult.failure("短信验证码不能为空").toMap();
        }
        if (oldpassword == null || "".equals(oldpassword)) {
            return WebResult.failure("旧密码不能为空").put("ERROR","OLDPASS").toMap();
        }
        if (newpassword == null || "".equals(newpassword)) {
            return WebResult.failure("新密码不能为空").put("ERROR","NEWPASS").toMap();
        }

        if (oldpassword.equals(newpassword)) {
            return WebResult.failure("旧密码与新密码一致").put("ERROR","NEWPASS").toMap();
        }

        SysUser user = sysUserService.selectByPrimaryKey(privilegeService.getCurrentPrincipal().getUserid());
        //如果旧密码不等于原始登录密码或者旧密码不等于原始提现密码
        if (!QEncodeUtil.md5Encrypt(oldpassword).equals(user.getPassword()) && !QEncodeUtil.md5Encrypt(oldpassword).equals(user.getTransferpassword())) {
            return WebResult.failure("旧密码错误，请重新输入").put("ERROR","OLDPASS").toMap();
        } else if (QEncodeUtil.md5Encrypt(newpassword).equals(user.getTransferpassword()) || QEncodeUtil.md5Encrypt(newpassword).equals(user.getPassword())) {
            return WebResult.failure("提现密码不能与登录密码一致").put("ERROR","OLDPASS").toMap();
        }

        VaildPhone validPhone = PhoneCodeCacheTimer.get(mobileCode);
        if (validPhone == null) {
            return WebResult.failure("验证码错误,请重新输入").toMap();
        } else if (validPhone.getValidTime() < new Date().getTime()) {
            PhoneCodeCacheTimer.remove(mobileCode);
            return WebResult.failure("短信验证码已过期，请重新获取").toMap();
        }else{
            if (user == null || "".equals(user.getMobile())) {
                return WebResult.failure("用户没有手机号码").toMap();
            }else if (!validPhone.getPhone().equals(user.getMobile())) {
                return WebResult.failure("与获取短信的手机号码一致").toMap();
            } else {
                PhoneCodeCacheTimer.remove(mobileCode);
            }
        }

        SysUser newUser = new SysUser();
        newUser.setUserid(user.getUserid());
        newUser.setAdminid(user.getUserid());
        newUser.setUpdatetime(new Date());
        if (passwordType == 1) {
            newUser.setPassword(QEncodeUtil.md5Encrypt(newpassword));
        } else if (passwordType == 2) {
            newUser.setTransferpassword(QEncodeUtil.md5Encrypt(newpassword));
        }

        if(sysUserService.updateByPrimaryKeySelective(newUser) > 0){
            return WebResult.success().toMap();
        }else{
            return WebResult.failure("更改密码失败，请与管理员联系").toMap();
        }
    }

}
